package cn.tedu.sims.service.impl;

import cn.tedu.sims.ex.ServiceException;
import cn.tedu.sims.mapper.*;
import cn.tedu.sims.pojo.dto.*;
import cn.tedu.sims.pojo.entity.Project;
import cn.tedu.sims.pojo.entity.ProjectInformation;
import cn.tedu.sims.pojo.vo.ProjectInformationVO;
import cn.tedu.sims.pojo.vo.ProjectReportTypeVO;
import cn.tedu.sims.pojo.vo.ProjectVO;
import cn.tedu.sims.security.LoginPrincipal;
import cn.tedu.sims.service.IProjectService;
import cn.tedu.sims.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class ProjectServiceImpl implements IProjectService {
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private ProjectInformationMapper projectInformationMapper;
    @Autowired
    private ProjectRejectMapper rejectMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private ProjectAuditMapper projectAuditMapper;
    /*
    * 申报
    * */
    @Override
    public void addNew(ProjectAndProjectInformationDTO projectAndProjectInformationDTO) {
        String reportProject = projectAndProjectInformationDTO.getReportProject();
        String reportType = projectAndProjectInformationDTO.getReportType();
        //通过项目名字跟类型查询是否存在
        if(reportProject==null){
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST,"请输入申报全称");
        }
        log.debug(reportProject,reportType);
        if(projectMapper.countByReportProject(reportProject,reportType)>0){
            String message = "该申报信息已存在";
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
        ProjectDTO projectDTO = new ProjectDTO();
        ProjectInformationDTO projectInformationDTO= new ProjectInformationDTO();
        BeanUtils.copyProperties(projectAndProjectInformationDTO,projectDTO);
        BeanUtils.copyProperties(projectAndProjectInformationDTO,projectInformationDTO);
        Project p = new Project();
        BeanUtils.copyProperties(projectDTO,p);
        String[] s = projectDTO.getReportYear().split("-");
        int y = Integer.parseInt(s[0])+1;
        p.setReportYear(""+y);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginPrincipal loginPrincipal  = (LoginPrincipal) authentication.getPrincipal();
        Long id = loginPrincipal.getId();
        log.debug("申报提交的id为：{}",id);
        p.setUserId(id);
        p.setReportTime(LocalDateTime.now());
        p.setGmtCreate(LocalDateTime.now());
        p.setReportState("待审核");
        projectMapper.insertProject(p);
        log.debug("接收到的projectInformation为:{}",projectInformationDTO);
        ProjectInformation projectInformation = new ProjectInformation();
        BeanUtils.copyProperties(projectInformationDTO,projectInformation);
        projectInformation.setProjectId(p.getId());
        projectInformationMapper.insertProjectInformation(projectInformation);
    }

    public void update(Project project){
        String reportProject = project.getReportProject();
        String reportType = project.getReportType();
        log.debug("修改获取{}",project);
        Long id = project.getId();
        log.debug("修改的名字，类型，id分别为：{}，{}，{}",reportProject,reportType,id);
        if(projectMapper.countByReportProjectAndNotId(reportProject,reportType,id)>0){
            String message = "修改的申报信息存在";
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }


        log.debug("ppp{}",project);
        String[] s = project.getReportYear().split("-");
        int y = Integer.parseInt(s[0])+1;
        project.setReportYear(""+y);
        project.setGmtModified(LocalDateTime.now());
        project.setReportState("待审核");
        projectMapper.update(project);

    }

    /*
    * 通过申报id获取详细信息
    * */
    @Override
    public ProjectInformationVO getProjectInformationVOByProjectId(Long projectId) {
        return projectInformationMapper.getProjectInformationVOByProjectId(projectId);
    }

    /*
    * 添加回驳信息
    * */
    @Override
    public void addNewProjectReject(ProjectRejectDTO projectRejectDTO) {
        projectMapper.stateFailById(projectRejectDTO.getProjectId());
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginPrincipal loginPrincipal  = (LoginPrincipal) authentication.getPrincipal();
        Long id = loginPrincipal.getId();
        rejectMapper.deleteByProjectId(projectRejectDTO.getProjectId());
        projectAuditMapper.delete(projectRejectDTO.getProjectId());

        projectAuditMapper.insert(projectRejectDTO.getProjectId(),id,LocalDateTime.now());
        rejectMapper.insert(projectRejectDTO);
    }

    @Override
    public String getRejectMessageByProjectId(int projectId) {
        return rejectMapper.getRejectMessageByProjectId(projectId);
    }

    @Override
    public ProjectVO getProject(long projectId) {
        return projectMapper.getBtId(projectId);
    }



    /*
    * 项目列表
    * */
    @Override
    public List<ProjectVO> projectList(String reportType) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginPrincipal loginPrincipal  = (LoginPrincipal) authentication.getPrincipal();
        Long id = loginPrincipal.getId();
        String username = loginPrincipal.getUsername();
        String s = roleMapper.roleByUsername(username);
        if(!s.equals("普通用户")){
            id = null;
        }
        log.debug("查询列表的id为：{}",id);
        return projectMapper.projectSelect(reportType,id);
    }



    /*
     * 根据id删除申报信息,详情,回驳信息
     */
    @Override
    public void deleteById(Long id) {
        projectMapper.deleteById(id);
        projectInformationMapper.deleteInformationById(id);
        rejectMapper.deleteByProjectId(id);
        projectAuditMapper.delete(id);
    }

    /*
    *根据年份,运营单位,审核状态查询列表
    * */
    @Override
    public List<ProjectVO> selectByYear(ProjectYearDTO project) {
        log.debug("*****************{}",project);
        if(project.getReportYear()!=""&&project.getReportYear()!=null){
            int y = Integer.parseInt(project.getReportYear().split("-")[0]) + 1;
            project.setReportYear(""+y);
        }
        System.out.println("project = " + project);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginPrincipal loginPrincipal  = (LoginPrincipal) authentication.getPrincipal();
        String username= loginPrincipal.getUsername();
        String s = roleMapper.roleByUsername(username);
        log.debug("模糊查询role:{}",s);
        if(s.equals("普通用户")){
            Long id = loginPrincipal.getId();
            project.setUserId(id);
            log.debug("用户Id为：{}",id);
        }else {
            project.setUserId(null);
        }
        return projectMapper.selectByYear(project);
    }
    @Override
    public List<ProjectVO> selectByAudit() {
        return projectMapper.selectByAudit();
    }


    @Override
    public ProjectVO selectById(Long id) {
        return projectMapper.selectById(id);
    }

    /**
     * 根据id删除申报,详情,回驳信息
     * */
    @Override
    public void deleteByIds(Long[] ids) {
        projectMapper.deleteByIds(ids);
        projectInformationMapper.deleteInformationByIds(ids);
        rejectMapper.deleteByProjectIds(ids);
        projectAuditMapper.deleteByIds(ids);
    }

    /**
     * 状态改为通过
     * */
    @Override
    public void stateOkById(long id) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginPrincipal loginPrincipal  = (LoginPrincipal) authentication.getPrincipal();
        Long auditId = loginPrincipal.getId();
        projectMapper.stateOkById(id);
       projectAuditMapper.insert(id,auditId,null);
    }

    /*
    * 状态改为拒绝
    * */
    @Override
    public void stateFailById(long id) {
        projectMapper.stateFailById(id);
    }


    /**
     * 通过项目类别查数量
     * @param
     * @return
     */
    @Override
    public ProjectReportTypeVO selectCountByType() {
        ProjectReportTypeVO projectReportTypeVO=new ProjectReportTypeVO();
        int project=projectMapper.selectCountByType("项目申报");
        int base=projectMapper.selectCountByType("基地申报");
        int unit=projectMapper.selectCountByType("单位申报");
        projectReportTypeVO.setProjectCount(project);
        projectReportTypeVO.setBaseCount(base);
        projectReportTypeVO.setUnitCount(unit);
        log.info("查询到的数为：{}",projectReportTypeVO);
        return projectReportTypeVO;
    }

    @Override
    public String[] selectPass() {
       String[] strings = new String[3];
       strings[0]= projectMapper.selectProjectPass();
        strings[1]=  projectMapper.selectBasePass();
        strings[2]=  projectMapper.selectUnitPass();
        return strings;
    }


}
